/* 
 * AUTHOR: Kevin Lam
 */

package com.apps.ubc.cc.ajax;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringEscapeUtils;

import com.apps.datastore.AccountInformationDatastore;
import com.apps.datastore.dao.SubscriptionFeedObject;
import com.apps.utils.FeedUtils;

public class FeedController extends HttpServlet {
	AccountInformationDatastore d = new AccountInformationDatastore();

	public void doGet(HttpServletRequest req, HttpServletResponse resp) {
		String touch = req.getParameter("touch");
		String type = req.getParameter("type");
		Cookie[] cookies = req.getCookies();
		String user = null;
		StringBuilder builder=new StringBuilder();
		builder.append("<feed>\n");
		//String feed = "<feed>\n";
		if (cookies != null) {
			for (int i = 0; i < cookies.length; i++) {
				if (cookies[i].getName().equals("user"))
					user = cookies[i].getValue();
			}
		}
		if (user != null && touch != null) {
			boolean setRead = false;
			boolean getUnreadOnly = false;
			if(touch.equals("true"))
				setRead = true;
			if(type.equals("unread"))
				getUnreadOnly = true;
			List<SubscriptionFeedObject> feedlist = d.readFeeds(user, setRead, getUnreadOnly);
			for(Iterator<SubscriptionFeedObject> i = feedlist.iterator(); i.hasNext();){
				SubscriptionFeedObject fo = i.next();
				builder.append("\t<message>\n");
				builder.append("\t\t<text>"+StringEscapeUtils.escapeHtml4(StringEscapeUtils.escapeXml(fo.getMessage()))+"</text>\n");
				builder.append("\t\t<timestamp>"+FeedUtils.timeBetween(fo.getTimestamp())+"</timestamp>\n");
				builder.append("\t\t<new>"+!fo.isRead()+"</new>\n");
				builder.append("\t</message>\n");
//				feed += "\t<message>\n";
//				feed += "\t\t<text>"+StringEscapeUtils.escapeHtml4(StringEscapeUtils.escapeXml(fo.getMessage()))+"</text>\n";
//				feed += "\t\t<timestamp>"+FeedUtils.timeBetween(fo.getTimestamp())+"</timestamp>\n";
//				feed += "\t\t<new>"+!fo.isRead()+"</new>\n";
//				feed +="\t</message>\n";
			}
		}
		else {
			//feed += "\t<error>Error while retrieving feeds</error>\n";
			builder.append("\t<error>Error while retrieving feeds</error>\n");
		}
		builder.append("</feed>");
		//feed += "</feed>";
		try {
			
			resp.setContentType("text/xml; charset=UTF-8");
			resp.getWriter().write(builder.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}
